/*
 * Copyright (c) 2010 Scott Morgan
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package captaintest;

import captaintest.util.FileUtil;
import com.thoughtworks.xstream.XStream;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class XmlCoverageDAO {
    private XStream x;

    public XmlCoverageDAO(){
        x = new XStream();
        
        x.alias("coverageDatabase", CoverageDatabase.class);
        x.alias("file", FileCoverage.class);
        x.alias("coverage", Coverage.class);
        x.useAttributeFor(CoverageDatabase.class, "lastUpdated");
        x.useAttributeFor(Coverage.class, "type");
        x.useAttributeFor(Coverage.class, "bestPercentCovered");
        x.useAttributeFor(Coverage.class, "bestCoveredLines");
        x.useAttributeFor(Coverage.class, "bestTotalLines");
        x.useAttributeFor(Coverage.class, "lastPercentCovered");
        x.useAttributeFor(Coverage.class, "lastCoveredLines");
        x.useAttributeFor(Coverage.class, "lastTotalLines");
        x.useAttributeFor(Coverage.class, "error");
        x.aliasField("type", Coverage.class, "type");
        x.addImplicitCollection(FileCoverage.class, "coverageList");
        
    }
    
    public String toXML(List<FileCoverage> fileCoverage){
        CoverageDatabase cd = new CoverageDatabase(fileCoverage);

        return x.toXML(cd);
    }

    public List<FileCoverage> fromXML(String xml){
        try {
            CoverageDatabase cd = (CoverageDatabase) x.fromXML(xml);
            return cd.getFileList();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<FileCoverage>();
        }
    }

    public void save(File f, List<FileCoverage> fileCoverage){
        Collections.sort(fileCoverage, new Comparator<FileCoverage>() {
            public int compare(FileCoverage o1, FileCoverage o2) {
                return o1.getFileName().compareTo(o2.getFileName());
            }
        });

        FileUtil.saveFile(f, toXML(fileCoverage));
    }

    public List<FileCoverage> load(File f){
        return fromXML(FileUtil.readFile(f));
    }

}
